//
//  EssentialInformationViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/9.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
//  完善基本信息
import UIKit
import DynamicBlurView
import Alamofire
import PKHUD
import SwiftyJSON

class EssentialInformationViewController: BaseViewController {
    @IBOutlet var borderViews: [UIView]!
    
    @IBOutlet weak var bgImageView: UIImageView!
    @IBOutlet weak var nickNameTextField: UITextField!
    @IBOutlet var genderSelectImages: [UIImageView]!
    
    @IBOutlet weak var dateBtn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
    }
    
    func setUI() {
        titleLabel(text: "完善基本信息", nil)
        let _ = borderViews.map({
            $0.layer.borderColor = UIColor.white.cgColor
            $0.layer.borderWidth = 1
        })
        
        nickNameTextField.attributedPlaceholder = NSAttributedString(string: "请填写昵称，不可修改", attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        
        let blurView = DynamicBlurView(frame: bgImageView.bounds)
        blurView.blurRadius = 10
        view.insertSubview(blurView, aboveSubview: bgImageView)
    }
    
    override func setNavigation() {
    }
    @IBAction func scrollTap(_ sender: Any) {
        let dateview = self.view.viewWithTag(900)
        dateview?.removeFromSuperview()
        self.nickNameTextField.resignFirstResponder()
    }
    
    @IBAction func maleTap(_ sender: UIButton) {
        genderSelectImages.first?.isHighlighted = true
        genderSelectImages.last?.isHighlighted = false
    }
    
    @IBAction func femaleTap(_ sender: UIButton) {
        genderSelectImages.first?.isHighlighted = false
        genderSelectImages.last?.isHighlighted = true
    }
    
    // 这里就用DatePicker
    @IBAction func birthdayTap(_ sender: UIButton) {
        let datepicker = UIDatePicker()
        datepicker.tag = 900
        datepicker.frame = CGRect(x: 0, y: self.view.frame.size.height-200, width: ScreenWidth, height: 200)
        self.view.addSubview(datepicker)
        
        // 属性设置
        datepicker.backgroundColor = UIColor.lightGray
        
        // 日期显示属性
        datepicker.datePickerMode = UIDatePickerMode.date
        
        // 设置默认时间
        datepicker.setDate(NSDate() as Date, animated: true)
        // 最小、最大时间选择设置
        datepicker.minimumDate = NSDate(timeIntervalSinceNow: -(60*60*24*365*120)) as Date
        datepicker.maximumDate = NSDate(timeIntervalSinceNow: 93312000) as Date
        
        // 将日期选择器区域设置为中文（默认显示英文）
        datepicker.locale = NSLocale(localeIdentifier: "zh_CN") as Locale
        
        // 添加方法
        datepicker.addTarget(self, action:#selector(dateChanged(datePicker:)), for: .valueChanged)
    }
    // MARK: - 日期选择器响应方法
    @objc func dateChanged(datePicker:UIDatePicker)
    {
        // 更新提醒时间文本框
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let date = datePicker.date
        let dateText = formatter.string(from: date)
        
        dateBtn.setTitle(dateText, for: UIControlState.normal)
    }
    // 下一步
    @IBAction func nextTap(_ sender: UIButton) {
        self.scrollTap(sender)
        
        if (self.nickNameTextField.text?.isEmpty)! {
            self.showToast(msg:"请输入昵称")
            return
        }
        if !(genderSelectImages.first?.isHighlighted)!,!(genderSelectImages.last?.isHighlighted)! {
            self.showToast(msg:"请选择性别")
            return
        }
        var gender:String = "男"
        if (genderSelectImages.last?.isHighlighted)! {
            gender = "女"
        }
        let birthdate:String = (dateBtn.titleLabel?.text!)!
        let requesturl = "\(BaseURL)\(updateUserInfoUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: ["nickname":nickNameTextField.text!,"sexy":gender,"birthday":birthdate] ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            if let result = response.result.value as? NSDictionary
                            {
                                let json = JSON(result)
                                if json["code"].int == 1{
                                    self.showToast(msg:"注册成功")
                                    
                                    let choicePreferenceVC = ChoicePreferenceViewController(nibName: "\(ChoicePreferenceViewController.self)", bundle: nil)
                                    self.navigationController?.pushViewController(choicePreferenceVC, animated: true)
                                    
                                }
                                else{
                                    self.showToast(msg:json["message"].string!)
                                }
                            }
                            
        }
        HUD.show(.label("加载中..."))
        
    }
    
    // 跳过
    @IBAction func skipTap(_ sender: UIButton) {
        let choicePreferenceVC = ChoicePreferenceViewController(nibName: "\(ChoicePreferenceViewController.self)", bundle: nil)
        self.navigationController?.pushViewController(choicePreferenceVC, animated: true)
    }
}
